use pyo3::prelude::*;
use pyo3::types::PyDict;
use reqwest::header::{CONTENT_TYPE, HeaderMap};
use serde::Serialize;


#[derive(Serialize)]
struct Body {
    a: String,
    b: String,
}

/// Post
#[pyfunction]
fn post_with_json(url: String, body: &PyDict) -> PyResult<(String, u16)> {
    let a: String = body.get_item("a").unwrap().extract()?;
    let b: String = body.get_item("b").unwrap().extract()?;

    let data = Body { a, b };

    let mut headers = HeaderMap::new();
    headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());

    let client = reqwest::blocking::Client::new();
    let resp = client.post(url).headers(headers).json(&data).send().unwrap();
    let status = resp.status().as_u16();


    Ok((resp.text().unwrap(), status))
}


/// A Python module implemented in Rust.
#[pymodule]
fn rust_http(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(post_with_json, m)?)?;
    Ok(())
}
